<?php
/**
 * Created by PhpStorm.
 * User: ysongyang
 * Date: 2016/6/7
 * Time: 10:50
 */
namespace Admin\Controller;
class CateProductController extends CommonController{

    function _initialize()
    {
        parent::_initialize();
        $this->_category = D('CateProduct');
    }

    //栏目分类首页
    public function index()
    {
        $this->cates = $this->_category->getCategoryTree();
        $this->display();
    }


    //添加栏目及添加栏目处理
    public function add()
    {
        if(IS_POST){
            if ($this->_category->add($_POST)) {
                $this->success('添加成功！', U(MODULE_NAME . '/CateProduct/index'));
            } else {
                $this->error('添加失败，请稍后再试！');
            }
        }else{
            $this->cate =  $this->_category->where(array('cate_pid'=>0))->select(); //获取顶级栏目数据
            $this->display();
        }
    }
    public function edit(){
        if(IS_POST){

            $res = $this->_category->where(array('cate_id'=>$_GET['cate_id']))->save($_POST);
            if($res){
                $this->success('更新栏目成功！', U(MODULE_NAME . '/CateProduct/index'));
            }else{
                $this->error('更新栏目失败，请稍后重试！');
            }
        }else{
            $this->cate = $this->_category->where(array('cate_pid'=>0))->select(); //获取顶级栏目数据
            $this->field = $this->_category->find($_GET['cate_id']);//查找当前栏目ID数据
            $this->display();
        }
    }

    //异步排序
    public function change(){
        //更新当前栏目的排序
        $res = $this->_category->where(array('cate_id'=>$_POST['cate_id']))->save(array('cate_order'=>$_POST['cate_order']));
        if($res){
            $data =['status'=>0,'info'=>'栏目排序更新成功！',];
        }else{
            $data = [
                'status'=>1,
                'info'=>'栏目排序更新失败，请稍后再试！',
            ];
        }
        $this->ajaxReturn($data);
    }
    //异步删除
    public function destroy($cate_id){
        //先查找当前栏目下是否有子栏目
        $count = $this->_category->where(array('cate_pid'=>$cate_id))->count();
        if($count > 0){
            $data = [
                'status'=>1,
                'info'=>'当前栏目下有子栏目，无法删除！',
            ];
        }else{
            $res = $this->_category->where(array('cate_id'=>$cate_id))->delete();
            if($res){
                $data =[
                    'status'=>0,
                    'info'=>'栏目删除成功！',
                ];
            }else{
                $data = [
                    'status'=>1,
                    'info'=>'栏目删除失败，请稍后再试！',
                ];
            }
        }
        $this->ajaxReturn($data);
    }
}